<template>
<section>

        <el-col :span="24" style="padding-top:10px;padding-bottom:10px;">
            <el-button round type="primary" @click="dialogFormVisible = true"  size="small" icon="el-icon-plus">新增角色</el-button> 
             
        </el-col>

        <el-dialog title="新增角色" @close="resetRoleForm('addRoleForm')" :visible.sync="dialogFormVisible" width="500px">
            <el-form :model="addForm" :rules="rules" ref="addRoleForm" size="small" label-width="80px"> 
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input clearable v-model="addForm.roleName"></el-input>
                    </el-form-item>  
                    <el-form-item label="备注" prop="realName">
                        <el-input clearable v-model="addForm.note"></el-input>
                    </el-form-item> 
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitRoleForm('addRoleForm')" :loading="loading">确 定</el-button>
            </div>
        </el-dialog>  

     <el-table
      v-loading="listLoading"
    border
    ref="multipleTable"
    :data="tableData"
    tooltip-effect="dark"
    style="width: 100%"
    @selection-change="handleSelectionChange">
    <el-table-column
      type="selection">
    </el-table-column>
    <el-table-column
    fixed
      prop="role"
      label="角色名称" 
      width="120px"
      show-overflow-tooltip>
    </el-table-column>
    <el-table-column
    fixed
      prop="status"
      label="状态" 
      width="120px"
      show-overflow-tooltip>
      <template slot-scope="scope">
        <el-tag
        size="mini"
          :type="scope.row.status == 1 ? 'success' : 'warning'"
          disable-transitions>{{scope.row.status==1?"可用":scope.row.status==5?"已禁用":"未分配权限"}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column
    fixed
      label="备注" 
      width="200px"
      prop="note" >
    </el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button
          size="mini"
          v-if="scope.row.type!=1"
          @click="handleSetMenu(scope.$index, scope.row)">分配权限</el-button>
           <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
          size="mini"
          v-if="scope.row.type!=1"
          @click="handleFore(scope.$index, scope.row)">{{scope.row.status==5?"解禁":"禁用"}}</el-button>
        <el-button
          size="mini"
          type="danger"
          v-if="scope.row.type!=1"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
   <el-col :span="24" class="toolbar">
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum">
        </el-pagination>
    </el-col>

    <el-dialog title="权限分配" @open="openDialog" @close="resetForm('addForm')" :visible.sync="showPremission" width="500px">
            <div>
              <el-tree
                :data="premissions"
                show-checkbox
                node-key="id"
                ref="tree"
                default-expand-all
                :default-checked-keys="checkedKeys"
                :props="defaultProps">
              </el-tree>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="showPremission = false">取 消</el-button>
                <el-button type="primary" @click="submitForm()" >确 定</el-button>
            </div>
        </el-dialog>  
</section>
</template>

<script>
import api from "@/service/api";
import http from "@/service/http";
//引用数据操作API
import store from '@/store'
//引用vuex的导入语法糖功能
import {createNamespacedHelpers} from 'vuex';
const {mapGetters,mapActions}=createNamespacedHelpers('system/role');

export default {
  data() {
    return {
      showPremission:false,
      premissions:[],
      checkedKeys:[],
      roleId:'',
      defaultProps: {
          children: 'child',
          label: 'name'
        },
        dialogFormVisible: false,
      loading: false,
      addForm: {
        type:0,//0:add  1:update
        roleName: "",
        note: ""
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" }
        ]
      },
    };
  },
  //计算属性
		computed:{
			//导入store的getters属性
      ...mapGetters(['tableData','currentPage','listLoading','totalNum','pageSize']),
      
		},
  methods: {
    //导入actions方法
		...mapActions(['getRoles','handleSelectionChange','handleSizeChange','handleCurrentChange']),
			
    handleEdit(index, row) {
        this.addForm.type = 1;
        this.addForm.id = row.id;
        this.dialogFormVisible = true;
        this.addForm.roleName = row.role;
        this.addForm.note = row.note;
    },
    handleDelete(index, row) {
        this.$confirm('确认删除角色 [ '+row.role+' ] 吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => { 
                     http.post(api.sysApi.delRoleStatus, row.id).then(data => {
                      if(!data.success){
                        return;
                      }
                       this.$message({
                            message: "删除成功",
                            type: "success"
                        });
                      this.getRoles();
                    });
                }).catch(() => {}); 
    },
    handleFore(index, row){
      let str = row.status == 5?"解禁":"禁用";
        this.$confirm('确认'+str+'角色 [ '+row.role+' ] 吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => { 
                    http.post(api.sysApi.updateRoleStatus, {id:row.id,status:row.status==5?row.preStatus:5,preStatus:row.status}).then(data => {
                      if(!data.success){
                        return;
                      }
                       this.$message({
                            message: "已"+str,
                            type: "success"
                        });
                      this.getRoles();
                    });
                }).catch(() => {});
    },
    handleSetMenu(index, row) {
      this.roleId = row.id;
      this.checkedKeys = row.menus;
      this.getSysMenu();
    },
    getSysMenu(){
      this.showPremission = true;
      http.post(api.sysApi.getSysMenu, "").then(data => {
            if(!data.success){
              return;
            }
            this.premissions = data.data;
          });
    },
    submitForm(){
        this.showPremission = false;
        let checkKeys = this.$refs.tree.getCheckedKeys();
        if(checkKeys.length==0){
             this.$message({
                message: "所选权限为空",
                type: "success"
             });
             return;
        }
         http.post(api.sysApi.setRolePermissions, {roleId:this.roleId,permissionIds:checkKeys}).then(data => {
            if(!data.success){
              return;
            }
            this.$message({
                message: "分配成功",
                type: "success"
             });
            this.getRoles();
          });
    },
    openDialog(){

    },
    resetForm(addFrom){

    },
    submitRoleForm(formName) { 
      this.$refs[formName].validate(valid => {
        if (valid) {
          var param = {
            role: this.addForm.roleName,
            note: this.addForm.note,
            id:0
          };
          if(this.addForm.type ==0){
              this.addRole(param);
          }else{
              this.updateRole(param);
          }
        } else {
          return false;
        }
      });
    },
     resetRoleForm(formName) { 
      this.addForm = {}; 
      this.$refs[formName].resetFields();
    },
    updateRole(param) { 
      param.id = this.addForm.id;
      http.post(api.sysApi.updateRole, param).then(data => {
        if(!data.success){
				return;
			}
        this.$message({
          showClose: true,
          message: "修改成功",
          type: "success"
        });
        //更新列表
        this.getRoles();
        this.dialogFormVisible = false; 
      });
    },
    addRole(param) { 
      http.post(api.sysApi.addRole, param).then(data => {
        if(!data.success){
				return;
			}
        this.$message({
          showClose: true,
          message: "添加成功",
          type: "success"
        });
        //更新列表
        this.getRoles();
        this.dialogFormVisible = false; 
      });
    }
  },
  mounted(){
       this.getRoles()
  }
};
</script>

<style>
.el-pagination {
  float: right;
} 
</style>
